﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Looptribe.Moodlin8.Model;
using Looptribe.WinRT.Toolkit;
using Windows.Storage.Pickers.Provider;

namespace Looptribe.Moodlin8.ViewModel
{
    public class FileOpenPickerViewModel : LoadingViewModel
    {
        public bool CanGoUp { get { return false; } }

        private readonly ObservableCollection<object> _files = new ObservableCollection<object>();
        public ObservableCollection<object> Files { get { return _files; } }

        private static string GetFileId(File file)
        {
            return file.FilePath + file.FileName;
        }

        public async void LoadContent()
        {
            if (!await Controller.LoginAsync())
                throw new InvalidOperationException("Login failed"); // TODO: redirect to login

            await Refresh();
        }

        public async override Task Refresh()
        {
            IsLoading = true;
            var response = (await Api.GetFilesAsync()).Data;
            IsLoading = false;

            if (response != null && response.Files != null)
                Files.AddMany(response.Files.Where(a => !a.IsDir).Select(a => new FileWrapper(a)));
        }

        public async Task AddFile(File file, FileOpenPickerUI ui)
        {
            var downloadedFile = (await Api.DownloadFileAsync(file)).Data;
            ui.AddFile(GetFileId(file), downloadedFile);
        }

        public void RemoveFile(File file, FileOpenPickerUI ui)
        {
            ui.RemoveFile(GetFileId(file));
        }
    }
}
